package com.elitel.frame.core.util;

import com.elitel.frame.core.common.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;

public class NashornUtil {

    /**
     * 执行 JavaScript 转换函数并返回转换后的对象
     *
     * @param inputObject 输入的对象，类型为 Object
     * @param jsBody      JavaScript 函数体代码，即 `transform` 方法中 `{}` 内的代码
     * @return 转换后的对象
     * @throws RuntimeException 如果执行 JavaScript 代码或处理 JSON 时发生异常
     */
    public static Object executeJsTransformation(Object inputObject, String jsBody) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        // 拼接完整的 JavaScript 函数
        String fullJsCode = "function transform(input) {" + jsBody + "}";
        try {
            engine.eval(fullJsCode);
            engine.put("input", inputObject);
            return engine.eval("transform(input)");
        } catch (ScriptException e) {
            throw new RuntimeException("执行 JavaScript 代码时发生异常", e);
        }
    }


    public static void main(String[] args) {
        Map<String, Object> inputObject = new HashMap<>();
        inputObject.put("name", "John");
        inputObject.put("age", 30);

        String[] strs = {
                "123", "456", "789", "000"
        };

        String jsBody = "return {fullName: 'Mr. ' + input.name, yearsOld: input.age};";

        //js对数组进行遍历+1
        String jsFunction = "var result = [];" +
                "for (var i = 0; i < input.length; i++) {" +
                "    result.push(input[i] + 1);" +
                "}" +
                "return result;";

        try {
            Object result = NashornUtil.executeJsTransformation(inputObject, jsBody);
            Object result1 = NashornUtil.executeJsTransformation(strs, jsFunction);
            System.out.println("转换后的对象: " + JsonUtil.ObjectToJson(result));
            System.out.println("转换后的对象: " + JsonUtil.ObjectToJson(result1));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}